package haltica.com.mx.ape.services.usuarios;

import haltica.com.mx.ape.domain.UserDetailsImpl;
import haltica.com.mx.ape.domain.UsuarioSistema;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service("userDetailsService")
public class UserDetailServiceImpl implements UserDetailsService {
	
	protected static final Logger log = LoggerFactory.getLogger(UserDetailServiceImpl.class);

	@Autowired
	private UserAssembler assembler;
	
	@Override
	public UserDetailsImpl loadUserByUsername(String username) 
			throws UsernameNotFoundException, DataAccessException {
		
		log.info("loadUserByUsername username: " + username);
		UsuarioSistema user;
		UserDetailsImpl userImpl;
		
		user = UsuarioSistema.findUsuarioSistemaByUsername(username);
		if (user == null) {
			log.error("Usuario no valido: " + username);
			throw new UsernameNotFoundException("Usuario no valido " + username);
		}
		
		
		userImpl = assembler.buildUserFromUsuarioSistema(user);
		return userImpl;
	}

}

